#完成底层的封装，find方法
import os

from appium.webdriver.common.mobileby import MobileBy
from appium.webdriver.webdriver import WebDriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from data_file_analysis.yaml_analysis import YamlAnalysis as ya
import datetime
from logs.logger import Logger

class Base():
    _black_list = [(By.ID, 'iv_close')]
    _error_count = 0
    _error_max = 10
    _verify_result = ''
    cur_path = os.path.abspath(os.path.dirname(__file__))  # 获取当前文件目录
    root_path = os.path.dirname(cur_path)
    time_now = datetime.datetime.now()
    time_now1 = f'{str(time_now.year)}_{str(time_now.month)}_{str(time_now.day)}_{str(time_now.hour)}_{str(time_now.minute)}'
    log = Logger(f'{root_path}/logs/info/{time_now1}_info.log', level='info')

    def __init__(self, driver:WebDriver = None):
        self.driver = driver

    #@black_wrapper
    def find(self, by_type, locator):
        self.driver.implicitly_wait(10)
        return self.driver.find_element(by_type, locator)

    def finds(self, by_type, locator):
        self.driver.implicitly_wait(10)
        return self.driver.find_elements(by_type, locator)

    def scroll_element(self, text):
        ui_text = f'new UiScrollable(new UiSelector().scrollable(true).instance(0)).' \
                  f'scrollIntoView(new UiSelector().text("{text}").instance(0))'
        ele = self.driver.find_element(MobileBy.ANDROID_UIAUTOMATOR, ui_text)
        self.log.logger.info(text)
        return ele

    def swipe_find(self, text, num=4):
        for i in range(0,num):
            if i == num-1:
                raise NoSuchElementException(f"找了{num-1}没有找到元素")

            try:
                return self.find(MobileBy.XPATH, f"//*[@text={text}]")
            except:
                print("未找到，滑动")
                size = self.driver.get_window_size()
                width = size['width']
                height = size['height']

                startx = width/2
                starty = height * 0.8
                endx = startx
                endy = height * 0.2

                duration = 2000

                self.driver.swipe(startx, starty, endx,endy,duration)

    #返回上一层目录
    def goback(self):
        self.driver.back()

    def steps(self, file_path, page_action, params:dict = None):
        steps:list[dict] = ya.return_yaml_data(file_path, page_action)

        self.log.logger.info(f'{page_action}:{steps},{params}')

        for step in steps:
            if "by" in step.keys():
                if step["by"] == "scroll_element":
                    element = self.scroll_element(step['locator'])
                else:
                    element = self.find(step["by"], step['locator'])

            if "action" in step.keys():
                if "click" == step["action"]:
                    element.click()
                if "send" == step["action"]:
                    '''
                    1.命中规则：传入的参数为键值对，且已给_params赋值，步骤里文件里的value命中_params的键值来命中
                    2.content_key:获取步骤value的值
                    3.根据content_key匹配_param_list的键值，将获取的参数赋值给content
                    4.将content内容send_keys到对应元素的文本框
                    '''
                    content_key = step["value"]
                    content = params[content_key]
                    element.send_keys(content)

    #设置页面cookies
    def set_cookies(self ,driver, file_path, data):
        cookies_dict = ya.return_yaml_data(file_path, data)
        for cookie in cookies_dict:
            if 'expiry' in cookie.keys():
                cookie.pop("expiry")
            driver.add_cookie(cookie)

    def element_click(self, by_type, locator):
        element = self.find(by_type, locator)
        element.click()

    #ActionChains操作
    def action_chains_click(self, by_type, locator):
        element = self.driver.find_element(by_type, locator)
        action = ActionChains(self.driver)
        action.move_to_element(element)
        action.click(element)
        action.perform()








